#!/bin/env python
# -*- coding:utf8 -*-
'''
Created on 2017��7��6��

@author: smly
需要安装winrar软件，并把winrar加入全局变量中
'''

import os
import calendar
import re
import shutil
from datetime import date, timedelta

clean_file_list = []
list_m = []


class Clean_Logs(object):
    def __init__(self):
        pass

    def get_curr_month_range(self, start_date=None):
        if start_date is None:
            start_date = date.today().replace(day=1)
            days_in_month = calendar.monthrange(start_date.year, start_date.month)
            end_date = start_date + timedelta(days=days_in_month[1])
        a_day = timedelta(days=1)
        first_day, last_day = (start_date, end_date)
        while first_day < last_day:
            list_m.append(str(first_day))
            first_day += a_day
        return list_m

    def get_last_month_range(self, start_date=None):
        if start_date is None:
            start_date = (date.today() - timedelta(days=date.today().day)).replace(day=1)
            days_in_month = calendar.monthrange(start_date.year, start_date.month)
            end_date = start_date + timedelta(days=days_in_month[1])
        a_day = timedelta(days=1)
        first_day, last_day = (start_date, end_date)
        while first_day < last_day:
            list_m.append(str(first_day))
            first_day += a_day
        return list_m

    def get_clean_file(self, p_reg, clean_dir):
        clean_file_list = []
        for clean_file in os.listdir(clean_dir):
            if not p_reg.findall(clean_file):
                clean_file_path = os.path.join(clean_dir, clean_file)
                clean_file_list.append(clean_file_path)
        return clean_file_list

    def clean_logs_files(self, file_path):
        try:
            os.remove(file_path)
            return True
        except Exception, e:
            print "delete error: %s" % e

    def compress_logs(self, logs_path):
        excute_cmd = 'winrar a %s.rar %s' % (logs_path, logs_path)
        result = os.system(excute_cmd)
        return result

    def clean_logs_dir(self, clean_logs_path):
        try:
            shutil.rmtree(clean_logs_path)
        except Exception:
            return False
        return True

if __name__ == '__main__':
    clean_file_list = []
    p = r'\d+-\d+-\d+.Info\.*(\d+)?(\.)?log'
    p_reg = re.compile(p, re.IGNORECASE)
    curr_dir = os.getcwd()
    cl = Clean_Logs()
    clean_dir = cl.get_last_month_range()
    for cpath in clean_dir:
        if os.path.exists(cpath):
            print cpath
            clean_files = cl.get_clean_file(p_reg, cpath)
            print clean_files
            if clean_files:
                for file_path in clean_files:
                    cl.clean_logs_files(file_path)
            else:
                print "%s: no log to clean!" % cpath
            result = cl.compress_logs(cpath)
            if result == 0:
                if cl.clean_logs_dir(cpath):
                    print 'remove %s sucess' % cpath
